﻿using System;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
using log4net;
using log4net.Config;
using Microsoft.Practices.Unity;
using SDCloudSolution.SDCloud.ModelRunAgent.Infrastructure.Interfaces;

namespace SDCloudSolution.SDCloud.ModelRunAgent
{
    public partial class SDCloudModelRunAgent : ServiceBase
    {
        private Thread activeThread;

        public SDCloudModelRunAgent()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            XmlConfigurator.Configure();
            var loggerInstance = LogManager.GetLogger("LOGGER");

            try
            {
                loggerInstance.Debug("Begin initialization process");

                var container = new UnityContainer();
                UnityConfig.Configurate(container);
                container.RegisterInstance(loggerInstance);

                activeThread = new Thread(async () =>
                {
                    try
                    {
                        var listener = container.Resolve<IModelQuequeListener>();
                        await listener.Listen();
                    }
                    catch(Exception e)
                    {
                        loggerInstance.Fatal("Unhandled exception into service main thread", e);
                    }
                });
                activeThread.Start();
                loggerInstance.Info("Service was started");
            }
            catch(Exception e)
            {
                loggerInstance.Fatal("Service has fatal error", e);
            }

            loggerInstance.Info("Service start complete");
        }

        protected override void OnStop()
        {
            var loggerInstance = LogManager.GetLogger("LOGGER");
            loggerInstance.Info("Service initialize an shutdowning");

            if (activeThread != null)
            {
                if (activeThread.IsAlive)
                {
                    try
                    {
                        activeThread.Abort();
                        loggerInstance.Info("Service thread successfully aborted");
                    }
                    catch(Exception e)
                    {
                        loggerInstance.Error("Service thread aborted with error", e);
                    }
                }
            }

            loggerInstance.Info("Service shutodwned");
        }
    }
}
